package com.iwhalecloud.bss.kite.cucc.service.inst;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.util.*;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.util.CommonUtil;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.bo.OrgInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.cucc.client.api.inst.IProdInstService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.CustInfoDetailQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ProdInstQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustBusiLicenseDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.UnicomRegionCache;
import com.iwhalecloud.bss.kite.cucc.service.cache.CuccCustInfoDetailCache;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.KiteAttrConfigCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteAttrConfig;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.DateUtil;
import com.ztesoft.bss.common.util.SpringUtil;

@Service
public class ProdInstService implements IProdInstService {

    @Value("${interface.call.mode:hsf}")
    private String mode;

    //String custId, String accNum, String pageNum, String pageSize
    @Override
    public UserQueryDTO listProdInst(Map<String, Object> paramMap) {
        String accNum = KiteMapUtils.getString(paramMap, "accNum");
        String custId = KiteMapUtils.getString(paramMap, "custId");
        String pageNum = KiteMapUtils.getString(paramMap, "pageNum");
        String pageSize = KiteMapUtils.getString(paramMap, "pageSize");
        String eparchyCode = KiteMapUtils.getString(paramMap, "eparchyCode");
        String provinceCode = KiteMapUtils.getString(paramMap, "provinceCode");

        UserQueryDTO userQueryDto = new UserQueryDTO();
        //工号
        String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
        //省份编码
        if(KiteStringUtils.isEmpty(eparchyCode)){
            eparchyCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        }
        if(KiteStringUtils.isEmpty(provinceCode)){
            provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        }
        //组织信息
        OrgInfo orgInfo=ContextUtil.getLoginInfo().getOrgInfo();

        UserInfo simpleLoginInfo = ContextUtil.getLoginInfo().getUserInfo();

        String bbssCustId = "";
        if(KiteStringUtils.isNotEmpty(accNum) && KiteStringUtils.isEmpty(custId)){
            Map<String,Object> userInfoMap = this.queryCustIdByAccNum(accNum,staffCode,provinceCode,eparchyCode);
            custId = KiteMapUtils.getString(userInfoMap, "CUST_ID");
            bbssCustId = KiteMapUtils.getString(userInfoMap, "BBSS_CUST_ID");
        }
        if (KiteStringUtils.isNotEmpty(custId)){
//            CustInfoDetailQryDTO custInfoDetailQryDto = new CustInfoDetailQryDTO();
            pageNum = !KiteStringUtils.isEmpty(pageNum)?pageNum:"1";
            pageSize = !KiteStringUtils.isEmpty(pageSize)?pageSize:"10";
            Integer intpageNum = Integer.parseInt(pageNum);
            Integer intPageSize = Integer.parseInt(pageSize);
            Map<String,Object> requestMap = new HashMap<String,Object>();
            requestMap.put("OP_CODE", "json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList");
            Map<String,Object> uniBssBodyMap = new HashMap<String,Object>();
            Map<String,Object> reqMap = new HashMap<String,Object>();
            reqMap.put("STAFF_CODE", staffCode);
            reqMap.put("CUST_ID", custId);
            reqMap.put("PROVINCE_CODE", provinceCode);
            reqMap.put("QRY_TYPE", "2");
            reqMap.put("SERVICE_TYPE_CODE", "");
            reqMap.put("PAGE_NUM", pageNum);
            reqMap.put("PAGE_SIZE", pageSize);
            reqMap.put("SERIAL_NUMBER", accNum);
//            省份62只查用户中心
            if(!"31".equals(provinceCode)||orgInfo.getOrgLevel()!=null&&orgInfo.getOrgLevel()==10){
                reqMap.put("QRY_SOURCE", "2");
            }
            if (KiteStringUtils.isNotEmpty(bbssCustId)) {
                List<Map<String, Object>> bbssCustLists = new ArrayList();
                Map<String, Object> bbssCustMap = new HashMap<String, Object>();
                bbssCustMap.put("PARA_ID", "bbssCustId");
                bbssCustMap.put("PARA_VALUE", bbssCustId);
                bbssCustLists.add(bbssCustMap);
                reqMap.put("PARA", bbssCustLists);
            }
            reqMap.put("USER_KIND", "1"); // 只查非成员用户

            //tcpCont
            Map<String,String> tcpContMap = new HashMap<String,String>();
            tcpContMap.put("APP_KEY", "");
            tcpContMap.put("TRANS_ID", "");
            reqMap.put("TCP_CONT", tcpContMap);
            uniBssBodyMap.put("REQ", reqMap);
            requestMap.put("UNI_BSS_BODY", uniBssBodyMap);
            InfServiceHelper.adaptGray(requestMap, reqMap);
            Map map;
            if (KiteStringUtils.isEqual(mode, "http")) {
                map = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_PRODINST_LIST.getCenterCode(),
                    LocalCallClientEnum.QRY_PRODINST_LIST.getServiceCode(), requestMap, null);
            }
            else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                String resultStr = infExchangeService.exchange(new JSONObject(requestMap));
                map = JSON.parseObject(resultStr, Map.class);
            }
            Map<String,Object> unibssHeadMap = (Map<String,Object>)map.get("UNI_BSS_HEAD");
            if (!KiteStringUtils.equals(KiteMapUtils.getString(unibssHeadMap, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)){
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(unibssHeadMap, "RESP_DESC"));
            }

            Map<String,Object> rspUniBssBodyMap = (Map<String,Object>)map.get("UNI_BSS_BODY");

            if(KiteMapUtils.isEmpty(rspUniBssBodyMap)){
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("返回报文缺少UNI_BSS_BODY节点");
            }
            Map<String,Object> rspMap = (Map<String,Object>)rspUniBssBodyMap.get("RSP");
            if (!KiteStringUtils.equals(KiteMapUtils.getString(rspMap,"RSP_CODE"), "0000")){
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(rspMap, "RSP_DESC"));
            }
            Map<String,Object> qryGrpUserListMap = (Map<String,Object>)rspMap.get("QRY_GRP_USER_LIST_RSP_BODY");
            Integer rowCount = KiteMapUtils.getInteger(qryGrpUserListMap, "ROW_COUNT");

            List<JSONObject> groupUserList = (List<JSONObject>)qryGrpUserListMap.get("GROUP_USER_LIST");
            List<ProdInstQryDTO> prodInstDtoList = new ArrayList<ProdInstQryDTO>();
            if (KiteListUtils.isNotEmpty(groupUserList)) {
                groupUserList.forEach(item -> {
                    ProdInstQryDTO prodInstQryDto = JSON.parseObject(item.toJSONString(), ProdInstQryDTO.class);
                    //开户时间处理
                    String openDate = prodInstQryDto.getOpen_date();
                    Date dOpenDate = DateUtil.strToDate(openDate);
                    openDate = DateUtil.format(dOpenDate);
                    prodInstQryDto.setOpen_date(openDate);
                    prodInstDtoList.add(prodInstQryDto);
                });
            }
            if(!Objects.nonNull(rowCount)){
                rowCount = prodInstDtoList.size();
            }
            //处理分页信息
            PageInfo<ProdInstQryDTO> resultPageInfo = new PageInfo<ProdInstQryDTO>();
            resultPageInfo.setList(prodInstDtoList);
            resultPageInfo.setPageNum(intpageNum);
            resultPageInfo.setPageSize(intPageSize);
            resultPageInfo.setTotal(rowCount);
            int pages = rowCount / intPageSize;
            if (rowCount % intPageSize != 0) {
                pages++;
            }
            resultPageInfo.setPages(pages);
            userQueryDto.setUserList(resultPageInfo);
            paramMap.put("custId", custId);

            //查询客户详情信息
//            CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(custId);

//            CuccCustInfoDetailDTO cuccCustInfoDTO = CuccCustInfoDetailCache.get(custId);
//            List<KiteAttrConfig> kiteAttrConfigList = KiteAttrConfigCache.get("29");
//            List<KiteAttrConfig> custFilterAttrConfigList = kiteAttrConfigList.stream().filter(kiteAttrConfig
//                ->{return KiteStringUtils.equals("29", kiteAttrConfig.getObjType());}).collect(Collectors.toList());
//
//            List<KiteAttr> kiteAttrList = custFilterAttrConfigList.stream().map(attrConfig
//                ->this.transKiteAttrConfigToKiteAttr(attrConfig)).collect(Collectors.toList());
//
//            List<KiteAttr> custInfoAttrList = this.dealCuccCustInfoDetailDTO(kiteAttrList,cuccCustInfoDTO);
//            custInfoDetailQryDto.setCustInfoAttr(custInfoAttrList);
//            custInfoDetailQryDto.setModuleName("集团客户姓名:" + cuccCustInfoDTO.getCustName());
//            userQueryDto.setCustInfo(custInfoDetailQryDto);
//            long time4 = System.currentTimeMillis();
//            System.out.println("deal cust info ============ " + (time4 - time3));
        }
        return userQueryDto;
    }

    @Override
    public void dealProdInstCustAttr(String custId, UserQueryDTO userQueryDTO) {
        if (KiteStringUtils.isBlank(custId)) {
            return;
        }
        CuccCustInfoDetailDTO cuccCustInfoDTO = CuccCustInfoDetailCache.get(custId);
        List<KiteAttrConfig> kiteAttrConfigList = KiteAttrConfigCache.get("29");
        List<KiteAttrConfig> custFilterAttrConfigList = kiteAttrConfigList.stream()
            .filter(kiteAttrConfig -> KiteStringUtils.equals("29", kiteAttrConfig.getObjType()))
            .collect(Collectors.toList());

        List<KiteAttr> kiteAttrList = custFilterAttrConfigList.stream().map(attrConfig
            ->this.transKiteAttrConfigToKiteAttr(attrConfig)).collect(Collectors.toList());
        CustInfoDetailQryDTO custInfoDetailQryDto = new CustInfoDetailQryDTO();
        List<KiteAttr> custInfoAttrList = this.dealCuccCustInfoDetailDTO(kiteAttrList,cuccCustInfoDTO);
        custInfoDetailQryDto.setCustInfoAttr(custInfoAttrList);
        custInfoDetailQryDto.setModuleName("集团客户姓名:" + cuccCustInfoDTO.getCustName());
        userQueryDTO.setCustInfo(custInfoDetailQryDto);
    }

    /**
     * 处理，把接口返回的信息设置到属性中
     * @param kiteAttrList
     * @param cuccCustInfoDTO
     */
     public List<KiteAttr> dealCuccCustInfoDetailDTO(List<KiteAttr> kiteAttrList,CuccCustInfoDetailDTO cuccCustInfoDTO){
         if(Objects.isNull(kiteAttrList) || Objects.isNull(cuccCustInfoDTO)){
             return kiteAttrList;
         }
         List<KiteAttr> resultList = new ArrayList<KiteAttr>();
         //客户编码(集团客户编码)
         KiteAttr groupIdAttr = this.createNewEmptyKiteAttr("groupId");
         groupIdAttr.setValue(cuccCustInfoDTO.getGroupId());
         groupIdAttr.setValueDesc(cuccCustInfoDTO.getGroupId());
         groupIdAttr.setCname("客户编码");
         resultList.add(groupIdAttr);

         //客户类型
         KiteAttr custTypeAttr = this.createNewEmptyKiteAttr("cust_class_type");
         custTypeAttr.setValue(cuccCustInfoDTO.getCustClassType());
         custTypeAttr.setValueDesc(cuccCustInfoDTO.getCustClassType());
         custTypeAttr.setCname("客户类型");
         if(KiteStringUtils.isNotEmpty(cuccCustInfoDTO.getCustClassType())){
             List<AttrValue> custTypeValues = AttrValueCache.get("2020110703");
             if (KiteListUtils.isNotEmpty(custTypeValues)){
                 for(AttrValue attrValue : custTypeValues){
                     if(KiteStringUtils.equals(cuccCustInfoDTO.getCustClassType(), attrValue.getAttrValue())){
                         custTypeAttr.setValueDesc(attrValue.getAttrValueName());
                     }
                 }
             }
         }
         resultList.add(custTypeAttr);

         //客户归属地市
         KiteAttr custEparchyAttr = this.createNewEmptyKiteAttr("eparchyCode");
         custEparchyAttr.setValue(cuccCustInfoDTO.getEparchyCode());
         custEparchyAttr.setValueDesc(cuccCustInfoDTO.getEparchyCode());
         custEparchyAttr.setCname("客户归属地市");
         if(KiteStringUtils.isNotEmpty(cuccCustInfoDTO.getEparchyCode())){
             UnicomRegion unicomRegion = UnicomRegionCache.getOneUnicomRegion(cuccCustInfoDTO.getEparchyCode());
             if(Objects.nonNull(unicomRegion)){
                 custEparchyAttr.setValueDesc(unicomRegion.getRegionName());
             }
         }
         resultList.add(custEparchyAttr);

         //营业执照
         String custBusiLicenseNum = "";
         CuccCustBusiLicenseDTO cuccCustBusiLicenseDto =  cuccCustInfoDTO.getCustBusiLicense();
         if(Objects.nonNull(cuccCustBusiLicenseDto)){
             custBusiLicenseNum = cuccCustBusiLicenseDto.getCertCode();
         }
         KiteAttr busiLicenseAttr = this.createNewEmptyKiteAttr("cust_busi_license");
         busiLicenseAttr.setValue(custBusiLicenseNum);
         busiLicenseAttr.setValueDesc(custBusiLicenseNum);
         busiLicenseAttr.setCname("营业执照");
         resultList.add(busiLicenseAttr);


         //cbss客户编码(custId)
         KiteAttr cbssCustIdAttr = this.createNewEmptyKiteAttr("cbssCustId");
         cbssCustIdAttr.setValue(cuccCustInfoDTO.getCustId());
         cbssCustIdAttr.setValueDesc(cuccCustInfoDTO.getCustId());
         cbssCustIdAttr.setCname("CBSS客户编码");
         resultList.add(cbssCustIdAttr);


         //联系人
         KiteAttr contactNameAttr = this.createNewEmptyKiteAttr("contact_name");
         contactNameAttr.setValue(cuccCustInfoDTO.getContactName());
         contactNameAttr.setValueDesc(cuccCustInfoDTO.getContactName());
         contactNameAttr.setCname("联系人");
         resultList.add(contactNameAttr);

         //联系电话
         KiteAttr contacPhoneAttr = this.createNewEmptyKiteAttr("contact_phone");
         contacPhoneAttr.setValue(cuccCustInfoDTO.getContactPhone());
         contacPhoneAttr.setValueDesc(cuccCustInfoDTO.getContactPhone());
         contacPhoneAttr.setCname("联系电话");
         resultList.add(contacPhoneAttr);

         //通信地址
         KiteAttr postAddrAttr = this.createNewEmptyKiteAttr("post_addr");
         postAddrAttr.setValue(cuccCustInfoDTO.getPostAddr());
         postAddrAttr.setValueDesc(cuccCustInfoDTO.getPostAddr());
         postAddrAttr.setCname("通信地址");
         resultList.add(postAddrAttr);
         return resultList;
     }

     public KiteAttr transKiteAttrConfigToKiteAttr(KiteAttrConfig kiteAttrConfig){
         KiteAttr kiteAttr = KiteBeanUtils.transform(kiteAttrConfig, KiteAttr.class);
         kiteAttr.setFieldName(kiteAttrConfig.getAttrField());
         kiteAttr.setAttrValueTypeId("TT");
         kiteAttr.setCname(kiteAttrConfig.getAttrName());
         return kiteAttr;
     }

     public KiteAttr createNewEmptyKiteAttr(String fieldName){
         KiteAttr kiteAttr = new KiteAttr();
         kiteAttr.setFieldName(fieldName);
         kiteAttr.setShowType("D");
         kiteAttr.setAttrValueTypeId("TT");
         kiteAttr.setColspan("1");
         return kiteAttr;
     }


    /**
     * 根据业务号码获取客户id
     * @param accNum
     * @return
     */
    public Map<String,Object> queryCustIdByAccNum(String accNum,String staffCode,String provinceCode,String eparchyCode) {
        Map<String,Object> uniBssBodyMap = new HashMap<String,Object>();
        Map<String,Object> reqMap = new HashMap<String,Object>();
        //tcp_cont
        Map<String,String> tcpContMap = new HashMap<String,String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        reqMap.put("TCP_CONT", tcpContMap);
        //国际工号，地市编码特殊处理
//        if(KiteStringUtils.isNotEmpty(provinceCode)&&provinceCode.startsWith("49")){
//            reqMap.put("EPARCHY_CODE", "497");
//        }else {
            reqMap.put("EPARCHY_CODE", eparchyCode);
//        }

        OrgInfo orgInfo=ContextUtil.getLoginInfo().getOrgInfo();
        if(!KiteObjectUtils.isEmpty(orgInfo)&&orgInfo.getOrgLevel()!=null&&orgInfo.getOrgLevel()==10){
            reqMap.remove("EPARCHY_CODE");
            reqMap.put("USER_SOURCE", "2");
        }
        if(!"31".equals(provinceCode)){
            reqMap.put("USER_SOURCE", "2");
        }
        reqMap.put("SERIAL_NUMBER", accNum);
        List<Map<String, String>> qryTagInfoList = new ArrayList<>();
        Map<String, String> qryTagInfo = new HashMap<>();
        qryTagInfo.put("TRANSLATE_FLAG", "1");
        qryTagInfo.put("VALID_FLAG", "1");
        qryTagInfo.put("TAG_NAME", "USER");
        qryTagInfoList.add(qryTagInfo);
        reqMap.put("QRY_TAG_INFOS", qryTagInfoList);
        reqMap.put("PROVINCE_CODE", provinceCode);
        reqMap.put("STAFF_CODE", staffCode);
        uniBssBodyMap.put("REQ", reqMap);
        Map<String,Object> requestMap = LocalTokenUtil.getParamMap(uniBssBodyMap);
        requestMap.put("OP_CODE", "json_bbssUserCenter_QryUserDetailServiceApi_qryUserDetailInfo");
        InfServiceHelper.adaptGray(requestMap, reqMap);

        String result;
        if (KiteStringUtils.isEqual(mode, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(requestMap));
        }
        Map<String, Object> rsp = JSON.parseObject(result, Map.class);
        Map<String, Object> uniBssHead = (Map<String, Object>) rsp.get("UNI_BSS_HEAD");
        if(!KiteStringUtils.equals(LocalInfConsts.RESP_SUCCESS, KiteMapUtils.getString(uniBssHead, "RESP_CODE"))){
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> rspUniBssBodyMap = (Map<String, Object>)rsp.get("UNI_BSS_BODY");
        if(KiteMapUtils.isEmpty(rspUniBssBodyMap)){
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("接口返回报文缺少UNI_BSS_BODY节点信息!");
        }

        Map<String,Object> rspMap = (Map<String,Object>)rspUniBssBodyMap.get("RSP");
        if(!KiteStringUtils.equals("0000", KiteMapUtils.getString(rspMap,"RESP_CODE"))){
            if (KiteStringUtils.equals("8888", KiteMapUtils.getString(rspMap,"RESP_CODE"))) {
                return null;
            }
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(rspMap, "RESP_DESC"));
        }

        Map<String,Object> userInfoMap = (Map<String,Object>)rspMap.get("USER_INFO");
        if(KiteMapUtils.isEmpty(userInfoMap)){
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("接口返回报文缺少USER_INFO节点信息!");
        }

        return userInfoMap;
     }

    /**
     * 根据业务号码获取查询号码是否在用
     * @param accNum
     * @return
     */
    public String queryUseAccNum(String accNum, String staffCode, String provinceCode, String eparchyCode) {
        Map<String, Object> uniBssBodyMap = new HashMap<String, Object>();
        Map<String, Object> reqMap = new HashMap<String, Object>();
        //tcp_cont
        Map<String, String> tcpContMap = new HashMap<String, String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        reqMap.put("TCP_CONT", tcpContMap);
        //国际工号，地市编码特殊处理
//        if(KiteStringUtils.isNotEmpty(provinceCode)&&provinceCode.startsWith("49")){
//            reqMap.put("EPARCHY_CODE", "499");
//        }else {
            reqMap.put("EPARCHY_CODE", eparchyCode);
//        }
        //云业务针对省级工号不传地市编码，只查用户中心
        OrgInfo orgInfo=ContextUtil.getLoginInfo().getOrgInfo();
        if(!KiteObjectUtils.isEmpty(orgInfo)&&orgInfo.getOrgLevel()!=null&&orgInfo.getOrgLevel()==10){
            reqMap.remove("EPARCHY_CODE");
            reqMap.put("USER_SOURCE","2");
        }
        if(!"31".equals(provinceCode)){
            reqMap.put("USER_SOURCE", "2");
        }
        reqMap.put("SERIAL_NUMBER", accNum);
        List<Map<String, String>> qryTagInfoList = new ArrayList<>();
        Map<String, String> qryTagInfo = new HashMap<>();
        qryTagInfo.put("TRANSLATE_FLAG", "1");
        qryTagInfo.put("VALID_FLAG", "1");
        qryTagInfo.put("TAG_NAME", "USER");
        qryTagInfoList.add(qryTagInfo);
        reqMap.put("QRY_TAG_INFOS", qryTagInfoList);
        reqMap.put("PROVINCE_CODE", provinceCode);
        reqMap.put("STAFF_CODE", staffCode);
        uniBssBodyMap.put("REQ", reqMap);
        Map<String, Object> requestMap = LocalTokenUtil.getParamMap(uniBssBodyMap);
        requestMap.put("OP_CODE", "json_bbssUserCenter_QryUserDetailServiceApi_qryUserDetailInfo");
        InfServiceHelper.adaptGray(requestMap, reqMap);

        String result;
        if (KiteStringUtils.isEqual(mode, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(requestMap));
        }
        Map<String, Object> rsp = JSON.parseObject(result, Map.class);
        Map<String, Object> uniBssHead = (Map<String, Object>) rsp.get("UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(LocalInfConsts.RESP_SUCCESS, KiteMapUtils.getString(uniBssHead, "RESP_CODE"))) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> rspUniBssBodyMap = (Map<String, Object>) rsp.get("UNI_BSS_BODY");
        if (KiteMapUtils.isEmpty(rspUniBssBodyMap)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("接口返回报文缺少UNI_BSS_BODY节点信息!");
        }

        Map<String, Object> rspMap = (Map<String, Object>) rspUniBssBodyMap.get("RSP");
        if (!KiteStringUtils.equals("0000", KiteMapUtils.getString(rspMap, "RESP_CODE"))) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(rspMap, "RESP_DESC"));
        }

        Map<String, Object> userInfoMap = (Map<String, Object>) rspMap.get("USER_INFO");
        if (KiteMapUtils.isEmpty(userInfoMap)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("接口返回报文缺少USER_INFO节点信息!");
        }
        String useAccNum = KiteMapUtils.getString(userInfoMap, "SERIAL_NUMBER");
        return useAccNum;
    }

    @Override
    public UserQueryDTO listCloudProdInst(Map<String, String> paramMap) {
        String accNum = KiteMapUtils.getString(paramMap, "accNum");
        String custId = KiteMapUtils.getString(paramMap, "custId");
        String pageNum = KiteMapUtils.getString(paramMap, "pageNum");
        String pageSize = KiteMapUtils.getString(paramMap, "pageSize");
        String eparchyCode = KiteMapUtils.getString(paramMap, "eparchyCode");
        String provinceCode = KiteMapUtils.getString(paramMap, "provinceCode");

        UserQueryDTO userQueryDto = new UserQueryDTO();
        //工号
        String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
        //省份编码
        if (KiteStringUtils.isEmpty(eparchyCode)) {
            eparchyCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        }
        if (KiteStringUtils.isEmpty(provinceCode)) {
            provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        }

        String bbssCustId = "";
        if (KiteStringUtils.isNotEmpty(accNum) && KiteStringUtils.isEmpty(custId)) {
            Map<String,Object> userInfoMap = this.queryCustIdByAccNum(accNum, staffCode, provinceCode, eparchyCode);
            custId = KiteMapUtils.getString(userInfoMap, "CUST_ID");
            bbssCustId = KiteMapUtils.getString(userInfoMap, "BBSS_CUST_ID");
        }

        if (KiteStringUtils.isNotEmpty(custId)) {
            CustInfoDetailQryDTO custInfoDetailQryDto = new CustInfoDetailQryDTO();
            pageNum = !KiteStringUtils.isEmpty(pageNum) ? pageNum : "1";
            pageSize = !KiteStringUtils.isEmpty(pageSize) ? pageSize : "10";
            Integer intpageNum = Integer.parseInt(pageNum);
            Integer intPageSize = Integer.parseInt(pageSize);
            Map<String, Object> requestMap = new HashMap<String, Object>();
            requestMap.put("OP_CODE", "json_bbssUserCenter_SalBusaGrpUserSerApi_qryGrpUserList");
            Map<String, Object> uniBssBodyMap = new HashMap<String, Object>();
            Map<String, Object> reqMap = new HashMap<String, Object>();
            reqMap.put("STAFF_CODE", staffCode);
            reqMap.put("CUST_ID", custId);
            reqMap.put("PROVINCE_CODE", provinceCode);
            reqMap.put("QRY_TYPE", "2");
            //            省份62只查用户中心，云业务受理针对49工号特殊处理不传地市编码，只查用户中心
            OrgInfo orgInfo=ContextUtil.getLoginInfo().getOrgInfo();
            if(!"31".equals(provinceCode)||orgInfo.getOrgLevel()!=null&&orgInfo.getOrgLevel()==10){
                reqMap.put("QRY_SOURCE", "2");
            }
            reqMap.put("SERVICE_TYPE_CODE", "");
            reqMap.put("PAGE_NUM", pageNum);
            reqMap.put("PAGE_SIZE", pageSize);
            reqMap.put("SERIAL_NUMBER", accNum);
            if (KiteStringUtils.isNotEmpty(bbssCustId)) {
                List<Map<String, Object>> bbssCustLists = new ArrayList();
                Map<String, Object> bbssCustMap = new HashMap<String, Object>();
                bbssCustMap.put("PARA_ID", "bbssCustId");
                bbssCustMap.put("PARA_VALUE", bbssCustId);
                bbssCustLists.add(bbssCustMap);
                reqMap.put("PARA", bbssCustLists);
            }
            //tcpCont
            Map<String, String> tcpContMap = new HashMap<String, String>();
            tcpContMap.put("APP_KEY", "");
            tcpContMap.put("TRANS_ID", "");
            reqMap.put("TCP_CONT", tcpContMap);

            uniBssBodyMap.put("REQ", reqMap);
            requestMap.put("UNI_BSS_BODY", uniBssBodyMap);
            InfServiceHelper.adaptGray(requestMap, reqMap);

            Map map;
            if (KiteStringUtils.isEqual(mode, "http")) {
                map = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_PRODINST_LIST.getCenterCode(),
                    LocalCallClientEnum.QRY_PRODINST_LIST.getServiceCode(), requestMap, null);
            } else {
                InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
                String resultStr = infExchangeService.exchange(new JSONObject(requestMap));
                map = JSON.parseObject(resultStr, Map.class);
            }

            Map<String, Object> unibssHeadMap = (Map<String, Object>) map.get("UNI_BSS_HEAD");
            if (!KiteStringUtils.equals(KiteMapUtils.getString(unibssHeadMap, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)) {
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(unibssHeadMap, "RESP_DESC"));
            }

            Map<String, Object> rspUniBssBodyMap = (Map<String, Object>) map.get("UNI_BSS_BODY");

            if (KiteMapUtils.isEmpty(rspUniBssBodyMap)) {
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("返回报文缺少UNI_BSS_BODY节点");
            }
            Map<String, Object> rspMap = (Map<String, Object>) rspUniBssBodyMap.get("RSP");
            if (!KiteStringUtils.equals(KiteMapUtils.getString(rspMap, "RSP_CODE"), "0000")) {
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(rspMap, "RSP_DESC"));
            }
            Map<String, Object> qryGrpUserListMap = (Map<String, Object>) rspMap.get("QRY_GRP_USER_LIST_RSP_BODY");
            Integer rowCount = KiteMapUtils.getInteger(qryGrpUserListMap, "ROW_COUNT");

            List<JSONObject> groupUserList = (List<JSONObject>) qryGrpUserListMap.get("GROUP_USER_LIST");

            List<ProdInstQryDTO> prodInstDtoList = new ArrayList<ProdInstQryDTO>();

            if (KiteListUtils.isNotEmpty(groupUserList)) {
                // 过滤是云业务的用户
                groupUserList = groupUserList.stream().filter(groupUser ->
                    KiteStringUtils.equalsAny(JSON.parseObject(groupUser.toJSONString(), ProdInstQryDTO.class).getGoods_id(), "50000003", "10002984", "10002985")).collect(Collectors.toList());
                groupUserList.forEach(item -> {
                    ProdInstQryDTO prodInstQryDto = JSON.parseObject(item.toJSONString(), ProdInstQryDTO.class);

                    //开户时间处理
                    String openDate = prodInstQryDto.getOpen_date();
                    Date dOpenDate = DateUtil.strToDate(openDate);
                    openDate = DateUtil.format(dOpenDate);
                    prodInstQryDto.setOpen_date(openDate);

                    prodInstDtoList.add(prodInstQryDto);


                });
            }

            if (!Objects.nonNull(rowCount)) {
                rowCount = prodInstDtoList.size();
            }
            //处理分页信息
            PageInfo<ProdInstQryDTO> resultPageInfo = new PageInfo<ProdInstQryDTO>();
            resultPageInfo.setList(prodInstDtoList);
            resultPageInfo.setPageNum(intpageNum);
            resultPageInfo.setPageSize(intPageSize);
            resultPageInfo.setTotal(rowCount);
            int pages = rowCount / intPageSize;
            if (rowCount % intPageSize != 0) {
                pages++;
            }
            resultPageInfo.setPages(pages);
            userQueryDto.setUserList(resultPageInfo);

            //查询客户详情信息

//            CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(custId);
            CuccCustInfoDetailDTO cuccCustInfoDTO = CuccCustInfoDetailCache.get(custId);
            List<KiteAttrConfig> kiteAttrConfigList = KiteAttrConfigCache.get("29");
            List<KiteAttrConfig> custFilterAttrConfigList = kiteAttrConfigList.stream().filter(kiteAttrConfig
                -> {
                return KiteStringUtils.equals("29", kiteAttrConfig.getObjType());
            }).collect(Collectors.toList());


            List<KiteAttr> kiteAttrList = custFilterAttrConfigList.stream().map(attrConfig
                -> this.transKiteAttrConfigToKiteAttr(attrConfig)).collect(Collectors.toList());

            List<KiteAttr> custInfoAttrList = this.dealCuccCustInfoDetailDTO(kiteAttrList, cuccCustInfoDTO);
            custInfoDetailQryDto.setCustInfoAttr(custInfoAttrList);
            custInfoDetailQryDto.setModuleName("集团客户姓名:" + cuccCustInfoDTO.getCustName());
            userQueryDto.setCustInfo(custInfoDetailQryDto);
        }
        return userQueryDto;
    }

    /**
     * 根据发起方业务号码，查询落地方/收费方业务号码，以及落地方/收费方业务号码归属省市
     * @author zhang.song
     * @date 2022-02-14 16:14
     * @param serialNumber 发起方业务号码
     * @param provinceCode 发起方省
     * @param cityCode 发起方地市
     * @param relationTypeCode 关系类型（07：收费方；08：落地方）
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    @Override
    public Map<String, String> queryChargeNumBySerialNumber(String serialNumber, String provinceCode, String cityCode, String relationTypeCode) {
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        //工号
        String staffCode = KiteMapUtils.getString(loginInfo.getUserInfo().getExtParams(), "account");
        //省份编码
        if(KiteStringUtils.isEmpty(provinceCode)) {
            provinceCode = loginInfo.getUserInfo().getPostProvinceNbr();
        }
        if(KiteStringUtils.isEmpty(cityCode)) {
            cityCode = loginInfo.getUserInfo().getPostLanId();
        }

        Map<String,Object> uniBssBodyMap = new HashMap<>();
        Map<String,Object> reqMap = new HashMap<String,Object>();
        // tcp_cont
        Map<String,String> tcpContMap = new HashMap<String,String>();
        tcpContMap.put("APP_KEY", LocalInfConsts.APP_ID);
        tcpContMap.put("TRANS_ID", LocalTokenUtil.getTransId());
        reqMap.put("TCP_CONT", tcpContMap);
        reqMap.put("EPARCHY_CODE", cityCode);

        OrgInfo orgInfo = loginInfo.getOrgInfo();
        if(!"31".equals(provinceCode)||(!KiteObjectUtils.isEmpty(orgInfo)&&orgInfo.getOrgLevel()!=null&&orgInfo.getOrgLevel()==10)){
            reqMap.remove("EPARCHY_CODE");
            reqMap.put("USER_SOURCE", "2");
        }
        reqMap.put("SERIAL_NUMBER", serialNumber);
        List<Map<String, String>> qryTagInfoList = new ArrayList<>();
        Map<String, String> qryTagInfo = new HashMap<>();
        qryTagInfo.put("TRANSLATE_FLAG", "1");
        qryTagInfo.put("VALID_FLAG", "1");
        qryTagInfo.put("TAG_NAME", "USER_RELATION_P");
        qryTagInfoList.add(qryTagInfo);
        reqMap.put("QRY_TAG_INFOS", qryTagInfoList);
        reqMap.put("PROVINCE_CODE", provinceCode);
        reqMap.put("STAFF_CODE", staffCode);
        uniBssBodyMap.put("REQ", reqMap);
        Map<String,Object> requestMap = LocalTokenUtil.getParamMap(uniBssBodyMap);
        requestMap.put("OP_CODE", "json_bbssUserCenter_QryUserDetailServiceApi_qryUserDetailInfo");
        InfServiceHelper.adaptGray(requestMap, reqMap);

        String result;
        if (KiteStringUtils.isEqual(mode, "http")) {
            result = HttpsCallClient
                .postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, requestMap, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(requestMap));
        }
        Map<String, Object> rsp = JSON.parseObject(result, Map.class);
        Map<String, Object> rspUniBssBodyMap = KiteMapUtils.getMap(rsp, "UNI_BSS_BODY");
        Map<String, Object> rspMap = KiteMapUtils.getMap(rspUniBssBodyMap, "RSP");

        Map<String, String> returnMap = new HashMap<>(8);
        List<Map<String, Object>> userRelationList = CommonUtil.getList(rspMap, "USER_RELATION_P_INFOS");
        if (KiteListUtils.isNotEmpty(userRelationList)) {
            for (Map<String, Object> userRelation : userRelationList) {
                if(KiteStringUtils.isEqual(relationTypeCode, KiteMapUtils.getString(userRelation, "RELATION_TYPE_CODE"))) {
                    String serialNumberB = KiteMapUtils.getString(userRelation, "SERIAL_NUMBER_B");
                    if(KiteStringUtils.isNotEmpty(serialNumberB)) {
                        returnMap.put("serialNumberB", serialNumberB);
                        returnMap.put("provinceCodeB", KiteMapUtils.getString(userRelation, "USER_B_PROVINCE_CODE"));
                        returnMap.put("cityCodeB", KiteMapUtils.getString(userRelation, "USER_B_EPARCHY_CODE"));
                        break;
                    }
                }

            }
        }
        return returnMap;
    }
}
